#coding=utf-8
import time
import ujson
import network
from ws_connection import ClientClosedError
from ws_server import WebSocketServer, WebSocketClient
import esp8266_auto_plant_flower as plant
import esp8266_key as key_hd
from machine import Pin;
from machine import WDT;
import machine
import gc
led_bule = Pin(13, Pin.OUT)    # create output pin on GPIO0
global server;
sys_time_start = time.time();
plt_obj = plant.plant_class()
def  get_humdt_json(obj):
    ctx = {}
    ctx['采集']=str(int(obj.humidity_avg))
    ctx['设置']=str(obj.set_hmdt_val)
    ctx['浇水']=str(obj.relay_on_ct)+'次'
    ctx['系统运行']=str(time.time() - sys_time_start)+'秒'
    ctx['剩余内存']=str(gc.mem_free())+'kb'
    ctx['版本']=str('1.1.5')
	# print(ujson.dumps(ctx))
    return ujson.dumps(ctx)

class TestClient(WebSocketClient):
    def __init__(self, conn):
        super().__init__(conn)

    def process(self):
        try:
            msg = self.connection.read()
            if not msg:
                return
            msg = msg.decode("utf-8")
            items = msg.split(" ")
            print("msg len="+ (msg))
            cmd = items[0]
            if cmd == "Hello":
                self.connection.write(cmd + " World")
                print("Hello World")
        except ClientClosedError:
            self.connection.close()
#处理对应的参数处理 /set?humidity=450
#处理对应的参数处理 /set?period=60
#处理对应的参数处理 /set?srvip=192.168.2.126
def handleset_humd(socket, args):
    print("handleset_humd--->"+str(args))
    # return;
    if 'humidity' in args:
        if int(args['humidity']) < 200 :
            server.response_ok(socket, "200", "set err humidity>200,period >60")
        else:
            plt_obj.set_hmdt_val = int(args['humidity'])
            plt_obj.plant_set_save()
            server.response_ok(socket, "200", "set humidity ok "+args['humidity'])
    elif  'period' in args :
        if  int(args['period']) < 60:
            server.response_ok(socket, "200", "set err humidity>200,period >60")
        else:
            plt_obj.set_push_period = int(args['period'])
            plt_obj.plant_set_save()
            server.response_ok(socket, "200", "set peroid ok "+args['period'])
    elif 'srvip' in args:
        if len(args['srvip']) == 0:
            server.response_ok(socket, "200", "set err push ip null")
        else:
            plt_obj.set_push_ip = args['srvip']
            plt_obj.plant_set_save()
            server.response_ok(socket, "200", "set push ip ok "+args['srvip'])
    else:
        server.err(socket, "400", "Bad Request")
#处理对应的参数处理 /get?humidity=0
#处理对应的参数处理 /get?settings=0
def handleGet(socket, args):
    print("handleGet-->"+str(args))
    if 'humidity' in args:
        resp = get_humdt_json(plt_obj)
        server.response_ok(socket, "200", str(resp))
    elif 'settings' in args:
        server.response_header(socket, "200")
        ctx={}
        ctx['set_hmdt']=str(plt_obj.set_hmdt_val)
        ctx['push_ip']=str(plt_obj.set_push_ip)
        ctx['push_period']=str(plt_obj.set_push_period)
        
        server.response_body(socket, ujson.dumps(ctx))
    else:
        server.err(socket, "400", "Bad Request")
#处理对应的参数处理 /cmd?led=[on|off]
def handleCmd(socket, args):
    print("handleCmd--->"+str(args))
    if 'led' in args:
        if args['led'] == 'on':
            led_bule.off() #取反
        elif args['led'] == 'off':
            led_bule.on()
        # updateInfo(socket)
        server.response_ok(socket, "200", str(args))
    else:
        # ESP8266WebServer.err(socket, "400", "Bad Request")
        server.err(socket, "400", "Bad Request")
class TestServer(WebSocketServer):
    def __init__(self):
        super().__init__("index.html", 2)#web默认html

    def _make_client(self, conn):
        return TestClient(conn)

def config_ap_init(ssid):
	ap = network.WLAN(network.AP_IF)
	ap.config(essid='bcg_'+ssid, password='bcg12345')
	ap.active(True)
def start_web():
    global plt_obj
    global server
    free_ct = 0
    # wdt = WDT()
    key_hd.key_init()
    plt_obj.plant_set_load()
    server = TestServer()
    server.set_handler_path("/get", handleGet)
    server.set_handler_path("/set", handleset_humd)
    server.start()
    #===
    config_ap_init(server.ap_str)
    
    try:
        while True:
            server.process_all()
            plant.run_poll_ms(plt_obj)
            time.sleep_ms(10)
            # wdt.feed()
            free_ct += 1
            if free_ct >= 1000: # 10s 回收一下内存
                gc.collect()
    except KeyboardInterrupt:
        pass
    server.stop()
# if __name__ == '__main__':
#     print("test call")
#     start_web()
